<script lang="ts" setup>
import { h, onMounted, ref, reactive } from 'vue';
import { getCurrentInstance, showLoading, hideLoading, showToast, redirectTo } from '@tarojs/taro';
import { Plus as AppNutIconPlus } from '@nutui/icons-vue-taro';
import { Button } from '@nutui/nutui-taro';
import dayjs from 'dayjs';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { QUERY_DICT_BY_PARENT_ID } from '/@/api/modules/base/dict';
import { INSERT_CHANGE_HANDLE } from '/@/api/modules/equipment/asset-change-handle';
import { formRules, state } from './state';
import { ASSET_DETAIL_QUERY } from '/@/api/modules/equipment/asset-manage';
const params = getCurrentInstance().router?.params as {
  assetId: string;
};

const handleEditFormRef = ref();

const formState = reactive<AssetChangeHandleApi.InsertChangeHandleReq>({
  changeTime: '',
  deptId: '',
  deptName: '',
  userId: '',
  userName: '',
  handleType: undefined,
  handleCost: '',
  handleIncome: '',
  assetList: [],
});

/**
 * @function 确认提交
 */
function submit() {
  handleEditFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;

    showLoading({ title: '加载中...' });
    INSERT_CHANGE_HANDLE(formState).then((res) => {
      hideLoading();
      showToast({
        title: res.comResp.msg || res.comResp.tip || '',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            redirectTo({ url: `/pages/asset-change/handle-detail/index?id=${res.changeId}` });
          }, 2000);
        },
      });
    });
  });
}

onMounted(() => {
  LOGIN_APP({}).then((res) => {
    formState.userId = res.sysUserDto.id;
    formState.userName = res.sysUserDto.name;
    formState.deptId = res.organDtos[0].id;
    formState.deptName = res.organDtos[0].name;
  });
  QUERY_DICT_BY_PARENT_ID({ parentTag: 'disposal_type' }).then((res) => {
    state.handleTypeList = res.content;
  });
  ASSET_DETAIL_QUERY({ ids: [params.assetId] }).then((res) => {
    formState.assetList.push({
      assetId: res.assetInfo?.id,
      assetName: res.assetInfo?.assetName,
      assetCode: res.assetInfo?.assetCode,
      assetDeptId: res.assetInfo?.organizationId,
      assetDeptName: res.assetInfo?.organizationName,
      assetOldStatus: res.assetInfo?.status,
      render: () => {
        return h(
          Button,
          {
            plain: true,
            size: 'mini',
            type: 'danger',
            onClick: () => {
              formState.assetList.splice(
                formState.assetList.findIndex((item) => {
                  return item.assetId === res.assetInfo?.id;
                }),
                1,
              );
            },
          },
          '删除',
        );
      },
    });
  });
});
</script>

<template>
  <view class="asset-handle-edit app-page--1">
    <app-navbar title="设备处置" />
    <nut-tabs
      model-value="push"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'record') {
            redirectTo({ url: '/pages/asset-change/handle-list/index' });
          }
        }
      "
    >
      <nut-tab-pane title="新增处置" pane-key="push" />
      <nut-tab-pane title="处置列表" pane-key="record" />
    </nut-tabs>
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="asset-handle-edit__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="asset-handle-edit__form"
          ref="handleEditFormRef"
        >
          <nut-form-item
            required
            prop="changeTime"
            label="处置时间"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="
                formState.changeTime ? dayjs(Number(formState.changeTime)).format('YYYY/MM/DD') : ''
              "
              placeholder="请选择处置时间"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.changeTimeCalendarIsShow = !state.changeTimeCalendarIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="handleType"
            label="处置状态"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="
                formState.handleType
                  ? state.handleTypeList[
                      state.handleTypeList.findIndex((item) => {
                        return item.dictOrder.toString() === formState.handleType?.toString();
                      })
                    ].dictName
                  : ''
              "
              placeholder="请选择处置状态"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.handleTypePickerIsShow = !state.handleTypePickerIsShow"
            />
          </nut-form-item>
          <nut-form-item
            prop="handleCost"
            label="处置成本"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.handleCost"
              placeholder="请输入处置成本"
              :border="false"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            prop="handleIncome"
            label="处置收入"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.handleIncome"
              placeholder="请输入处置收入"
              :border="false"
              input-align="right"
            />
          </nut-form-item>

          <nut-form-item
            required
            prop="assetList"
            label-width="0"
            label-align="left"
            error-message-align="left"
          >
            <nut-table
              class="asset-handle-edit__table"
              bordered
              striped
              :columns="[
                { title: '设备编号', key: 'assetCode' },
                { title: '设备名称', key: 'assetName' },
                { title: '所属部门', key: 'assetDeptName' },
                { title: '操作', key: 'render' },
              ]"
              :data="formState.assetList"
            />
            <nut-button
              block
              plain
              shape="round"
              type="info"
              @click="state.appAssetListPopupIsShow = !state.appAssetListPopupIsShow"
            >
              <template #icon>
                <app-nut-icon-plus />
              </template>
              <text>添加设备</text>
            </nut-button>
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>

    <view class="asset-handle-edit__footer">
      <nut-button block type="info" @click="submit">
        <text>提交</text>
      </nut-button>
    </view>

    <nut-popup v-model:visible="state.handleTypePickerIsShow" position="bottom">
      <nut-picker
        title="请选择处置状态"
        :model-value="[formState.handleType]"
        :columns="
          state.handleTypeList.map((item) => {
            return { value: item.dictOrder, text: item.dictName };
          })
        "
        @confirm="
          ({ selectedValue, selectedOptions }) => {
            if (!selectedValue[0]) return;

            formState.handleType = selectedOptions[0].value;
            state.handleTypePickerIsShow = false;
          }
        "
        @cancel="state.handleTypePickerIsShow = false"
      />
    </nut-popup>

    <nut-calendar
      v-model:visible="state.changeTimeCalendarIsShow"
      :start-date="dayjs().format('YYYY-MM-DD')"
      :default-value="dayjs(formState.changeTime).format('YYYY-MM-DD')"
      @choose="(date: string | string[]) => {
        formState.changeTime = dayjs(date[3]).valueOf().toString();
      }"
    />
    <app-asset-list-popup
      v-model="state.appAssetListPopupIsShow"
      title="处置设备"
      :options="{
        status: [2, 5, 6],
      }"
      @on-selected="(assetItem: AssetInfo.Dto) => {
        if (formState.assetList.findIndex((item) => { return item.assetId === assetItem.id }) >= 0) return;

        formState.assetList.push({
          assetId: assetItem.id,
          assetName: assetItem.assetName,
          assetCode: assetItem.assetCode,
          assetDeptId: assetItem.organizationId,
          assetDeptName: assetItem.organizationName,
          assetOldStatus: assetItem.status,
          render: () => {
            return h(Button, { plain: true, size: 'mini', type: 'danger', onClick: () => {
              formState.assetList.splice(formState.assetList.findIndex((item) => { return item.assetId === assetItem.id }), 1)
            } }, '删除');
          },
        })

        showToast({ title: '添加设备成功!', icon: 'success', duration: 1000 });
      }"
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
